package com.android.webcamsViewer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WebcamAdder extends Activity {
	// Static attributes
	private static final String TAG = "WebcamAdder";
	private static final int WEBCAM_ADDER = 1;

	// Private attributes
	private Button webcamSaveButton;
	private EditText webcamNameEditText;
	private EditText webcamUrlEditText;
	private int position;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.adder);
		
		// Get position of image
		Bundle extras = getIntent().getExtras();
		position = extras.getInt("position");
		
		// Form items handlers
		webcamNameEditText = (EditText) findViewById(R.id.webcamNameEditText);
		webcamUrlEditText = (EditText) findViewById(R.id.webcamUrlEditText);
		webcamSaveButton = (Button) findViewById(R.id.webcamSaveButton);
		
		// Set name and url in text boxes
		WebcamList list = new WebcamList(this.getApplicationContext());
		if (list.getLength() > 0 && position > -1) {
			Webcam webcam = list.getWebcam(position);
			webcamNameEditText.setText(webcam.getName());
			webcamUrlEditText.setText(webcam.getUrl());
		}

		// Add event listener to buttons
		webcamSaveButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				onSaveButtonClicked();
			};
		});

	}

	/**
	 * Handler Save Button
	 */
	public void onSaveButtonClicked() {
		if (validate()) {
			String url = webcamUrlEditText.getText().toString();
			String name = webcamNameEditText.getText().toString();
			WebcamList list = new WebcamList(this.getApplicationContext());

			// Update info webcam based on position
			if(position > -1) 
				list.updateWebcam(position, name, url);
			else 
				list.createWebcam(name, url);
			
			// Check Grid Images to refresh it
			Intent i = new Intent();
			i.putExtra("refresh", true);
			setResult(RESULT_OK, i);
			// Close UI
			this.finish();
		} else {
			Toast.makeText(this.getApplicationContext(),
					getText(R.string.addError), Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Validate method
	 */
	public boolean validate() {
		String url = webcamUrlEditText.getText().toString();
		String name = webcamNameEditText.getText().toString();
		return (!url.equals("") && !name.equals(""));
	}
}
